package epam.marchenko.library.services;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import epam.marchenko.library.domain.Book;
import epam.marchenko.library.domain.OutcomeRecord;
import epam.marchenko.library.domain.User;
import epam.marchenko.library.repository.OutcomeRecordRepository;

@Service
public class OutcomeRecordServiceImpl implements OutcomeRecordService {

	@Autowired
	OutcomeRecordRepository outcomeRep;
	
	public void addOutcomeRecord(OutcomeRecord record) {
		outcomeRep.create(record);
	}

	
	public List<OutcomeRecord> getAllOutcomeRecords() {
		return outcomeRep.findAll();
	}

	public List<OutcomeRecord> getAllOutcomeRecordsForBook(Book book) {
		return outcomeRep.findForBook(book);
	}


	@Override
	public boolean isRecordClosable(OutcomeRecord record) {
		OutcomeRecord fullRecord;
			fullRecord = outcomeRep.find(record); 
		if (fullRecord==null) return false;
		return fullRecord.isActive();
	}

	public List<OutcomeRecord> getActiveOrdersForUser(User user) {
		List<OutcomeRecord> orlist = outcomeRep.findForUser(user);
		Iterator<OutcomeRecord> oiter = orlist.iterator();
		while (oiter.hasNext()) {
			OutcomeRecord or = oiter.next();
			if (!or.isActive())
				oiter.remove();
		}
		return orlist;
	}


	@Override
	public double countPrice(OutcomeRecord record) {
		Date rd = record.getReturnDate();
		Date sd = record.getStartDate();
		int days = Days.daysBetween(new DateTime(sd), new DateTime(rd)).getDays();
		double price = days*record.getBook().getBookClass().getRent();
		return price;
	}


	@Override
	public OutcomeRecord find(OutcomeRecord record) {
		return outcomeRep.find(record);
	}


	@Override
	public void deleteOutcomeRecordById(int id) {
		outcomeRep.deleteById(id);
	}
}
